<?php
require ('nusoap/nusoap.php');
function smsGateway($User_ID, $Message, $Service_ID, $Command_Code,$Request_ID) {
	global $HTTP_RAW_POST_DATA;
	$result='';
	
	$connect=mysql_connect("localhost", "mysql", "hanoi2006") or die(mysql_error());
	mysql_select_db("wap") or die(mysql_error());
	mysql_query("SET NAMES 'utf8'");
	//insert lg_soap
	$sql_soap="insert into wp_soap(soap_user_id,	soap_message,soap_service_id,soap_command_code,soap_request_id,soap_raw_request,remote_addr,created,modified) values ('".$User_ID."','".$Message."','".$Service_ID."','".$Command_Code."','".$Request_ID."','".$HTTP_RAW_POST_DATA."','".@$_SERVER['REMOTE_ADDR']."',now(),now())";
	try{
		$ret = mysql_query($sql_soap) or die(mysql_error());
		if($ret === true){
			$soap_id=mysql_insert_id();
		}else{
			throw new Exception("can't insert wp_soap");
		}
		
		 //end insert lg_soap
		if(!in_array($Service_ID, array("7049","7149","7549","7649","7749"))){
			throw new Exception("Not Support ".$Service_ID);
		}
		if(strtoupper($Command_Code)!=='WAP'){
			throw new Exception("Invalid Command Code!");
		}
		$Message2 = str_replace ( "20%", " ", $Message );
		$Message3=explode(" ",$Message2);
		if( (count($Message3)>1&&count($Message3)<3) && strtoupper($Message3[0])==="WAP"){
			$post_id=mysql_real_escape_string($Message3[1]);
			
			$sql ="select meta_value from wp_postmeta WHERE post_id ='".$post_id."' and meta_key ='_wp_attached_file'";
		    $rs = mysql_query($sql) or die($sql.'('.mysql_error().')');
		    $num_rows = mysql_num_rows($rs);
		    if ($num_rows){
			    $row = mysql_fetch_row($rs);
			    $result="Ban da nhan link file http://wap.moba.vn/wp-content/uploads/".$row[0]; 
			   	$sql_soap_update ="UPDATE wp_soap SET result='".$result."' WHERE id =".$soap_id;
		        $ret1 = mysql_query($sql_soap_update);
	        }
	      	mysql_close($connect);
  
		}else {
			throw new Exception("Invalid Message!");
		}
	}catch(Exception $ex){
		$result = 'error';
		$sql_soap_update ="UPDATE wp_soap SET result='".$result."',is_error=1,error_detail = '".$ex->getMessage()."' WHERE id =".$soap_id;
         $ret = mysql_query($sql_soap_update);
         mysql_close($connect);
	}
	return $result;
}
$server = new soap_server ();
$server -> configureWSDL ( 'smsGateway', 'urn:message' );
$server -> register ( 
					"smsGateway", 
					array (
								'User_ID' => 'xsd:string', 
								'Message' => 'xsd:string', 
								'Service_ID' => 'xsd:string', 
								'Command_Code' => 'xsd:string', 
								'Operator' => 'xsd:string',
								'Request_ID' => 'xsd:string' ), array ('result' => 'xsd:string' ), 'urn:message', 
					'urn:message#smsGateway' );
$HTTP_RAW_POST_DATA = isset ( $HTTP_RAW_POST_DATA ) ? $HTTP_RAW_POST_DATA : '';
$server -> service ( $HTTP_RAW_POST_DATA );
?>